package BasicClient;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;


/**
 * This class implements the forbes protocol for requests to the server
 * @author pokeefe
 *
 */
public class ServerImpl implements Server {

	private Socket sock;
	private DataOutputStream out;
	private DataInputStream in;
	
	public ServerImpl(String addr, int port, Client client) throws UnknownHostException, IOException{	
		this.sock = new Socket(addr, port);
		this.out = new DataOutputStream(sock.getOutputStream());
		this.in = new DataInputStream(sock.getInputStream());
		IncomingRequestHandlerThread t = new IncomingRequestHandlerThread(sock, client);
		t.start();	
	}
	
	@Override
	public void actionCall(int playerID) {
		try {
			out.writeByte(Constants.PlayerBroadcastConstants.ACTION_CALL_HEADER);
			out.writeInt(playerID);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void actionRaise(int playerID, int amount) {
		try {
			out.writeByte(Constants.PlayerBroadcastConstants.ACTION_RAISE_HEADER);
			out.writeInt(playerID);
			out.writeInt(amount);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void actionFold(int playerID) {
		try {
			out.writeByte(Constants.PlayerBroadcastConstants.ACTION_FOLD_HEADER);
			out.writeInt(playerID);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void actionCheck(int playerID) {
		// not in the protocol yet		
	}

	@Override
	public void requestBlinds(int playerID) {
		try {
			out.writeByte(Constants.PlayerBroadcastConstants.REQUEST_BLINDS_HEADER);
			out.writeInt(playerID);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void requestSeat(int playerID) {
		try {
			out.writeByte(Constants.PlayerBroadcastConstants.REQUEST_ID_HEADER);
			out.writeInt(playerID);
			out.writeShort(Constants.PlayerBroadcastConstants.SPECIAL_TABLE_ID);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void requestPlayerId() {
		try {
			out.writeByte(Constants.PlayerBroadcastConstants.REQUEST_ID_HEADER);
			out.writeInt(Constants.PlayerBroadcastConstants.SPECIAL_PLAYER_ID);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}	
}
